const { app, BrowserWindow, ipcMain } = require('electron')
const { autoUpdater } = require('electron-updater');
const path = require('path')
const url = require('url')
const os = require('os')
let win = null; 
function createWindow() {
	win = new BrowserWindow({
		width: 1920,
		height: 1080,
		frame: false,
		title: '自助机', 
		fullscreen: true,
		webPreferences: {
			nodeIntegration: true,
			contextIsolation: false, 
			enableRemoteModule: true,
		}
	})  
	console.log("🚀 ~ createWindow ~ process.env.NODE_ENV == 'development':", process.env.NODE_ENV == 'development')
	if (process.env.NODE_ENV == 'development') {
		win.loadURL('http://192.168.31.109:5173/')
			.catch(err => {
				console.log("🚀 ~ createWindow development ~ err:", err)
			});
	} else {
		win.loadURL(url.format({
			protocol: 'file',
			slashes: true,
			pathname: path.join(__dirname, 'dist/build/h5/index.html')
		})).catch(err => {
			console.log("🚀 ~ createWindow production ~ err:", err)
		});
	} 

	console.log("🚀 ~ createWindow ~ win.loadURL:", path.join(__dirname, 'dist/build/h5/index.html'))
	if (process.env.NODE_ENV == 'development')
		win.webContents.openDevTools();
	// 阻止窗口关闭
	win.on('close', (e) => {
		// 阻止默认行为，即不关闭窗口
		// e.preventDefault(); 
		win = null
	});
}




// 添加更新相关的事件处理
function setupAutoUpdater() {
	autoUpdater.autoDownload = false;
	autoUpdater.autoInstallOnAppQuit = false;

	// 配置更新服务器地址
	autoUpdater.setFeedURL({
		provider: 'generic',
		url: 'https://syfy.xyqp.cn.com/updates/' // 替换为您的更新服务器地址
	});

	// 检查更新错误
	autoUpdater.on('error', (err) => {
		win.webContents.send('update-error', err);
	});

	// 检查更新
	autoUpdater.on('checking-for-update', () => {
		win.webContents.send('checking-for-update');
	});

	// 有可用更新
	autoUpdater.on('update-available', (info) => {
		win.webContents.send('update-available', info);
	});

	// 没有可用更新
	autoUpdater.on('update-not-available', (info) => {
		win.webContents.send('update-not-available', info);
	});

	// 更新下载进度
	autoUpdater.on('download-progress', (progressObj) => {
		win.webContents.send('download-progress', progressObj);
	});

	// 更新下载完成
	autoUpdater.on('update-downloaded', (info) => {
		win.webContents.send('update-downloaded', info);
	});
}


app.whenReady().then(() => {
	createWindow()
	setupAutoUpdater();
	app.on('activate', function () {
		if (BrowserWindow.getAllWindows().length === 0) createWindow()
	}) 
}) 

app.on('window-all-closed', function () {
	if (process.platform !== 'darwin') app.quit()
})

// 直接退出应用的功能
ipcMain.handle('quitApp', () => {
	app.quit();
});

// 打开任务管理器
ipcMain.handle('openTaskManager', () => {
	const { exec } = require('child_process');
	exec('taskmgr');
});

// 获取版本号
ipcMain.handle('getVersion', async () => {
	return { version: app.getVersion() };
});

// 添加IPC处理程序来响应前端的更新请求
ipcMain.handle('checkForUpdates', async () => {
	try {
		console.log('ipcMain checkForUpdates');
		await autoUpdater.checkForUpdates();
		return { success: true };
	} catch (error) {
		console.error('检查更新失败:', error);
		return { success: false, error: error.message };
	}
});

// 下载更新
ipcMain.handle('downloadUpdate', () => {
	autoUpdater.downloadUpdate();
});

// 安装更新
ipcMain.handle('installUpdate', async () => {
	autoUpdater.quitAndInstall();
});

// 打印发票
ipcMain.handle('handlePrintInvoice', async (e, data) => {
	console.log("🚀 ~ ipcMain.handle ~ data:", data)
	const printWindow = new BrowserWindow({
		show: false,
		width: 950,
		height: 550,
		webPreferences: {
			nodeIntegration: true,
			contextIsolation: false,
			enableRemoteModule: true,
			webSecurity: false
		}
	});
	// Load the content into the new window
	printWindow.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(data.html)}`);
	// Wait for the window to finish loading before printing
	printWindow.webContents.on('did-finish-load', () => {
		// Print the content
		printWindow.webContents.print(data, () => {
			// Close the window after printing
			printWindow.close();
			printWindow.destroy();
			win.webContents.send('printInvoiceCallback', true);
		});
	});
});


ipcMain.handle('getPrinterList', async (e, data) => {
	const list = await win.webContents.getPrintersAsync();
	return list;
});

// 添加新的IPC处理函数
ipcMain.handle('getDeviceInfo', async () => {
	try {
		const deviceInfo = {
			deviceName: os.hostname(),    // 获取设备名称
			deviceId: getDeviceId()      // 获取设备ID
		};
		return deviceInfo;
	} catch (error) {
		console.error('获取设备信息失败:', error);
		return null;
	}
});

// 获取设备ID的辅助函数
function getDeviceId() {
	const networkInterfaces = os.networkInterfaces();
	// 使用第一个找到的非内部MAC地址作为设备ID
	for (const interfaceName in networkInterfaces) {
		const interfaces = networkInterfaces[interfaceName];
		for (const interface of interfaces) {
			if (!interface.internal && interface.mac !== '00:00:00:00:00:00') {
				return interface.mac.replace(/:/g, ''); // 移除MAC地址中的冒号
			}
		}
	}
	return os.hostname(); // 如果无法获取MAC地址，则返回主机名作为备选
}